package top.withwings.bonus.bonus.pojo.bonus.rule;

import top.withwings.bonus.bonus.pojo.BonusForm;
import top.withwings.bonus.bonus.pojo.Rate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

public class HighPriceBonusRule extends SingleBonusRule{

    public static final String TYPE = "HIGH-PRICE";

    private int maxLevel;

    public HighPriceBonusRule(int id, String name, LinkedHashMap<String, Double> paramMap) {
        super(id, name, paramMap);
        this.type = TYPE;
        initMaxLevel();
    }

    private void initMaxLevel() {

        for(int i = 0  ; i <100 ; i++){
            if(this.paramMap.get("x"+(i+1)) == null){
                this.maxLevel = i ;
                break;
            }
        }

    }

    @Override
    public Rate applyOn(BonusForm bonusForm) {

        double price = bonusForm.getPrice();

        double standardPrice = bonusForm.getGood().getStandardPrice();

        double highRate = price * 100.0/ standardPrice;

        for(int  i = maxLevel ; i >0 ; i --){
            if(highRate >= this.paramMap.get("x"+ i)){
                return new Rate(Rate.TYPE_NORMAL, this.paramMap.get("y"+ i));
            }

        }
        return Rate.NOT_APPLIED;

    }

    @Override
    public void check(){
        List<String> xParamKeys = new ArrayList<>();

        for (String s : this.paramMap.keySet()) {
            if(s.startsWith("y")){
                continue;
            }
            else xParamKeys.add(s);
        }

        Collections.sort(xParamKeys);

        for(int i=0 ; i < xParamKeys.size()-1 ;i++){
            if(this.paramMap.get(xParamKeys.get(i))>=this.paramMap.get(xParamKeys.get(i+1))){
                throw new IllegalArgumentException("相对于参考价格的比例必须逐级增加");
            }
        }



    }
}

